# Post a thread with posts from a CSV dump
# by Cee Pee

import collections
from copy import copy
import re
import time
import forumapi

def settings(settings):
	settings.add_option("--tags", type="list", help="tags add to the thread", metavar="NAMES")
	settings.add_arg("file", help="CSV file")
	settings.add_arg("forum", type="int", help="forum ID to post in", metavar="ID")

Post = collections.namedtuple("Post", "postid _ _ username userid title time content _ _ _ _ _ _ _ _ _ _", rename=True)

def main(me, options, args):
	print("Opening {args.file} to be posted in forum {args.forum}".format(args=args))
	f = open(args.file, mode="rb")
	
	raw = f.read().decode(me.site.encoding, "ignore")
	raw = raw.replace('\\"', '"')
	raw = re.sub(r"(?<!\\)'", "'''", raw)
	
	raw_posts = raw.replace("\r\n", "\r").split("\n")
	#print(repr(raw_posts[0]))
	
	posts = []
	for raw_post in raw_posts:
		if raw_post:
			try:
				posts.append(eval("Post({0})".format(raw_post.replace("\r", "\n"))))
			except Exception as e:
				print(e)
				return
	
	first_post = True
	for post in posts:
		print("Posting message {post.postid}".format(post=post))
		
		message = "[quote={post.username} ({post.postid} @ {date})]{post.content}[/quote]".format(post=post, date=time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(int(post.time))))
		
		if first_post:
			if options.tags:
				me.module.get_attr("Tag")
			
			t = me.make_thread(message, post.title, args.forum, tags=options.tags)
			first_post = False
			
			pp_template = me.prepare_post(t=t)
		else:
			prepared_post = copy(pp_template)
			prepared_post.message = message
			if post.title:
				prepared_post.title = post.title
			prepared_post.submit()

if __name__ == "__main__":
	forumapi.run(main, options=settings, supported_types=["vbulletin"])
